/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.modules.apps.controller.AppController.java 
 * <p>
 * 类产生时间: 2014/4/29 0029 下午 22:27
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.modules.apps.controller;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.econsole.common.util.MD5Util;
import com.oceansoft.mobile.econsole.modules.apps.entity.AppInfo;
import com.oceansoft.mobile.econsole.modules.apps.entity.AppVersion;
import com.oceansoft.mobile.econsole.modules.apps.service.IAppInfoService;
import com.oceansoft.mobile.econsole.modules.apps.service.IAppVersionService;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.file.service.ISysFileService;
import com.oceansoft.mobile.econsole.modules.message.entity.ExceptionCommonBase;
import com.oceansoft.mobile.econsole.modules.message.entity.PushMessage;
import com.oceansoft.mobile.econsole.modules.message.service.PushMessageService;
import com.oceansoft.mobile.econsole.modules.sys.service.ISysDictService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * 应用App管理业务控制器
 *
 * @author: chenw
 * @time: 2014/4/29 0029 下午 22:27
 */
@Controller
@RequestMapping("sys/app")
public class AppController extends BaseController {

    @Resource
    private IAppInfoService appInfoService;

    @Resource
    private IAppVersionService appVersionService;

    @Resource
    private ISysFileService fileService;

    @Resource
    private ISysDictService dictService;

    @Resource
    private PushMessageService pushMessageService;

    /**
     * 主程序版本升级
     *
     * @return String 应用APK上传界面
     */
    @RequestMapping(value = "upgrade", method = GET)
    public String gotoAppUpgrade(Query query, Model model) {
        query.setNumPerPage(8);
        Pager pager = appVersionService.findChannelByPage(query);
        model.addAttribute("query", query).addAttribute("pager", pager);
        return "apps/app-upgrade";
    }

    @RequestMapping(value = "upgrade/list", method = POST)
    public String gotoAppUpgradeList(Query query, Model model) {
        query.setNumPerPage(8);
        Pager pager = appVersionService.findChannelByPage(query);
        model.addAttribute("query", query).addAttribute("pager", pager);
        log(String.format("查看版本信息列表第%d页", query.getPageNum()));
        return "apps/app-upgrade";
    }

    /**
     * 保存版本信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "version/save", method = POST)
    public Result saveVersion(AppVersion appVersion) {
        return appVersionService.save(appVersion, getLocalHostIP());
    }

    /**
     * 上传APP更新安装包
     *
     * @param request MultipartHttpServletRequest
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "pkg/upload", method = POST)
    public Result uploadUpgradeApp(MultipartHttpServletRequest request) {
        String appId = null;
        MultipartFile apk = request.getFile("apk");
        if (null == apk) {
            return new Result(Result.FAILURE, "请选择升级安装包文件");
        }

        try {
            appId = MD5Util.getMD5String(apk.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "上传升级安装包失败");
        }

        return fileService.saveFile(getLocalHostIP(), "-1", appId, "apk", apk);
    }

    /**
     * 应用列表
     *
     * @param model 应用列表
     * @return String
     */
    @RequestMapping(value = "list", method = GET)
    public String gotoAppIndex(Query query, Model model) {
        query.setOrderField("sort");
        query.setOrderDirection("asc");
        Pager pager = appInfoService.findByPage(new Query());
        model.addAttribute("query", query);
        model.addAttribute("pager", pager);
        return "apps/app-list";
    }

    /**
     * 列表分页显示
     *
     * @param query 分页查询条件
     * @param model 数据Model
     * @return 页面地址
     */
    @RequestMapping(value = "list", method = POST)
    public String loadAppByPage(Query query, Model model) {
        Pager pager = appInfoService.findByPage(query);
        model.addAttribute("query", query);
        model.addAttribute("pager", pager);
        return "apps/app-list";
    }

    /**
     * 进入快撤理赔管理模块
     *
     * @return String
     */
    @RequestMapping(value = "accident", method = GET)
    public String gotoAccidentClimIndex(Query query, Model model) {
        query.setOrderField("sort");
        query.setOrderDirection("asc");
        Pager pager = appInfoService.findByPage(new Query());
        model.addAttribute("query", query);
        model.addAttribute("pager", pager);
        log("查看应用列表");
        return "app/app-accident";
    }

    /**
     * 进入应用新增或查看应用页面
     *
     * @return 新增页面URL
     */
    @ResponseBody
    @RequestMapping(value = "new", method = POST)
    public Result addApp(AppInfo appInfo, Model model) {
        log(String.format("新增第三方应用[ %s ]，ID=%d", appInfo.getTitle(), appInfo.getId()));
        return appInfoService.save(appInfo, getLocalHostIP());
    }

    /**
     * 应用图标上传
     *
     * @param request MultipartHttpServletRequest
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "icon/upload", method = POST)
    public Result uploadIcon(MultipartHttpServletRequest request) {
        String iconId = request.getParameter("iconId");
        MultipartFile icon = request.getFile("appIcon");
        if (null == icon)
            return new Result(Result.FAILURE, "请选择插件图标文件");
        if (!StringUtils.hasText(iconId) || "0".equals(iconId)) {
            try {
                iconId = DigestUtils.md5DigestAsHex(icon.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(Result.FAILURE, "上传应用插件图标失败");
            }
        }
        return fileService.saveFile(getLocalHostIP(), getSession().getId(), iconId, "icon", icon);
    }

    /**
     * 上传应用插件文件
     *
     * @param request MultipartHttpServletRequest
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "plugin/upload", method = POST)
    public Result uploadPlugin(MultipartHttpServletRequest request) {
        String _pluginId = request.getParameter("pluginId");
        MultipartFile _plugin = request.getFile("appPlugin");
        if (null == _plugin)
            return new Result(Result.FAILURE, "请选择插件文件");
        if (!StringUtils.hasText(_pluginId) || "0".equals(_pluginId)) {
            try {
                _pluginId = DigestUtils.md5DigestAsHex(_plugin.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(Result.FAILURE, "上传应用插件失败");
            }
        }
        log(String.format("%s上传应用插件", getSession().getLoginId()));
        return fileService.saveFile(getLocalHostIP(), getSession().getId(), _pluginId, "plugins", _plugin);
    }

    /**
     * 应用图标删除
     *
     * @param icon_id 删除图标ID
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "icon/del/{icon_id}", method = POST)
    public Result deleteAppIcon(@PathVariable("icon_id") String icon_id) {
        return fileService.deleteByFileId(icon_id);
    }

    /**
     * 进入应用新增或查看应用页面
     *
     * @return 新增页面URL
     */
    @RequestMapping(value = "view/{app_id}", method = GET)
    public String viewApp(@PathVariable("app_id") int appId, Model model) {
        if (0 == appId) {//新增
            AppInfo appInfo = new AppInfo();
            appInfo.setId(0);
            model.addAttribute("app", new AppInfo());
            model.addAttribute("buttonText", "选择");
            return "apps/app-detail";
        } else {
            AppInfo app = appInfoService.findAppBaseInfoById(appId);
            model.addAttribute("app", app);
            model.addAttribute("buttonText", "更新");
            model.addAttribute("iconUrl", configInfo.getFileDownloadUrl(app.getIcon()));
            model.addAttribute("iconId", app.getIcon().replace("icon/", "").replace(".png", ""));
            model.addAttribute("pluginId", app.getUrl() == null?"":app.getUrl().replace("plugins/", "").replace(".zip", "").replace(".apk", ""));
            return "apps/app-detail";
        }
    }

    /**
     * 更新应用信息
     *
     * @param appInfo AppInfo
     * @return 编辑页面URL
     */
    @ResponseBody
    @RequestMapping(value = "edit", method = POST)
    public Result editApp(AppInfo appInfo, HttpServletRequest request) {
        appInfo.setModTime(new Date());
        if (0 == appInfo.getId()) {
            appInfoService.save(appInfo, getLocalHostIP());
        } else {
            appInfoService.update(appInfo, getLocalHostIP());
        }
        JSONObject extra = new JSONObject();
        extra.put("appid", appInfo.getId());
        extra.put("status", 1);
        extra.put("remoteversion", appInfo.getVersionCode());
        try {
            pushMessageService.saveMessage("应用状态更新", PushMessage.PushType.BROADCAST, null, null, "plugin_updated", PushMessage.ContentType.UPDATE_INFO, extra.toJSONString(),"android");
        } catch (ExceptionCommonBase exceptionCommonBase) {
            exceptionCommonBase.printStackTrace();
        }
        log(String.format("更新第三方应用[ %s ]，ID=%d", appInfo.getTitle(), appInfo.getId()));
        return new Result();
    }

    @ResponseBody
    @RequestMapping(value = "del/{app_id}", method = DELETE)
    public Result delApp(@PathVariable("app_id") int appId) {
        appInfoService.deleteAppById(appId);
        JSONObject extra = new JSONObject();
        extra.put("appid", appId);
        extra.put("status", 2);
        extra.put("remoteversion", -1);
        try {
            pushMessageService.saveMessage("删除应用插件", PushMessage.PushType.BROADCAST, null, null, "plugin_updated", PushMessage.ContentType.UPDATE_INFO, extra.toJSONString(),"android");
        } catch (ExceptionCommonBase exceptionCommonBase) {
            exceptionCommonBase.printStackTrace();
        }
        log(String.format("删除第三方应用，ID=%d", appId));
        return new Result();
    }
}
